//
//  BaseViewController.m
//  KidReading
//
//  Created by telen on 14/12/10.
//  Copyright (c) 2014年 刘赞黄Telen. All rights reserved.
//

#import "BaseViewController.h"

#import "ConstDefine.h"


@interface TLDebugDeallocView : UIView
@end
@implementation TLDebugDeallocView
- (void)dealloc
{
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
#endif
}
@end


@interface BaseViewController ()<VCTransitionsDelegate>
- (void)presentToPopViewController:(PopBaseViewController*)popvc;
- (BOOL)shouldAutorotate;
@end
@implementation BaseViewController
{
    BaseAnimation* _animation;
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (void)dealloc
{
    self.tracPageName = nil;
#if __Debug_is_dealloced_log
    NSLog(@"dealloc: %@",NSStringFromClass([self class]));
    NSLog(@"self.view Retain %d",(int)self.view.getRetainCount);
#endif
    [BaseVCManager unRegisterBaseVC:self];
}

- (void)dealloc_My
{
#if __Debug_is_dealloced_log
    NSLog(@"self.view Retain %d",(int)self.view.getRetainCount);
#endif
//    [self.view removeAllSubViews];
}

- (void)initZZZ
{
    if (_animation) {
        return;
    }
    [BaseVCManager registerBaseVC:self];
    //base添加title(清除)
    //NSString* title = NSStringFromClass([self class]);
    //if ([title hasSuffix:@"ViewController"]) {
        //title = [title stringByReplacingOccurrencesOfString:@"ViewController" withString:@"_Scence"];
    //}
    //self.title = [NSString stringWithFormat:@"%@",title];
    //
    self.rotation = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
    self.tracPageName = NSStringFromClass([self class]);
    //
    _animation = [[ModalAnimation alloc] init];
    _animation.delegate = self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        [self initZZZ];
    }
    return self;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self initZZZ];
    }
    return self;
}

- (void)toRotation:(NSNumber*)rtn
{
    if (![NSThread isMainThread]) {
        [self performSelectorOnMainThread:@selector(toRotation:) withObject:rtn waitUntilDone:NO];
        return;
    }
    UIInterfaceOrientation rotation = [rtn intValue];
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = rotation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];//perform 的传参表达方式
    }
}

- (UIInterfaceOrientation)deviceRotation
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(orientation)]) {
        SEL selector = NSSelectorFromString(@"orientation");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        UIInterfaceOrientation orientation =  UIInterfaceOrientationUnknown;
        [invocation invoke];//perform 的传参表达方式
        [invocation getReturnValue:&orientation];
        return orientation;
    }
    return UIInterfaceOrientationUnknown;
}

- (void)forceOrientationTo:(UIInterfaceOrientation)rotation
{
    if (rotation == UIInterfaceOrientationLandscapeRight
        || rotation == UIInterfaceOrientationLandscapeLeft) {
        [self setMyRotationToHorizontal];
    }else{
        [self setMyRotationToVertical];
    }
    
    //rotation
    UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
    UIInterfaceOrientation deviceOrientation = [self deviceRotation];
    if ([self isRotationHorizontal:rotation] != [self isRotationHorizontal:statusBarOrientation]) {
        if (deviceOrientation == rotation) {
            [self toRotation:[NSNumber numberWithInteger:statusBarOrientation]];
            [self performSelector:@selector(toRotation:) withObject:[NSNumber numberWithInteger:rotation] afterDelay:0.3f];
        }else{
            [self toRotation:[NSNumber numberWithInteger:rotation]];
        }
    }
}

- (CGSize)forceToOrientation:(UIInterfaceOrientation)rotation
{
    //Ref
    CGFloat w = self.view.bounds.size.width;
    CGFloat h = self.view.bounds.size.height;
    
    if (rotation == UIInterfaceOrientationLandscapeRight
        || rotation == UIInterfaceOrientationLandscapeLeft) {
        [self setMyRotationToHorizontal];
    }else{
        [self setMyRotationToVertical];
    }
    
    //rotation
    UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
    if ([self isRotationHorizontal:rotation] != [self isRotationHorizontal:statusBarOrientation] ) {
        [self toRotation:[NSNumber numberWithInteger:rotation]];
    }
    
    if (w < h &&(UIInterfaceOrientationLandscapeLeft == rotation
                 || UIInterfaceOrientationLandscapeRight == rotation)) {
        CGFloat temp = w;
        w = h;
        h = temp;
    }
    if (w > h &&(UIInterfaceOrientationPortrait == rotation
                 || UIInterfaceOrientationPortraitUpsideDown == rotation)) {
        CGFloat temp = w;
        w = h;
        h = temp;
    }
    
    width_my = w;
    height_my = h;
    return CGSizeMake(w, h);
}

- (void)setMyRotationToVertical
{
    self.rotation = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
}

- (void)setMyRotationToHorizontal
{
    self.rotation = UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

- (void)setMyRotationToAllMask
{
    self.rotation = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}

- (BOOL)isRotationHorizontal:(UIInterfaceOrientation)rotation
{
    BOOL ret = YES;
    if (rotation == UIInterfaceOrientationPortrait
        || rotation == UIInterfaceOrientationPortraitUpsideDown) {
        ret = NO;
    }
    return ret;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    if ([DataProcessing iOS7_low]) {
        CGRect frame = [DataProcessing exchangeWH:self.view.bounds];
        self.view.frame = frame;
    }
#if __Debug_is_dealloced_log
    TLDebugDeallocView* tldebguview = [[TLDebugDeallocView alloc] init];
    tldebguview.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tldebguview];
    tldebguview.translatesAutoresizingMaskIntoConstraints = NO;
    [tldebguview lyt_alignToParent];
#endif
    //
    width_my = self.view.frame.size.width;
    height_my = self.view.frame.size.height;
    width_my > height_my ? (width_short = height_my, height_long = width_my) :(height_long = height_my, width_short = width_my);
    //
    ratio_w = 768/width_short;
    ratio_h = 1024/height_long;
    //
    ratio_iPhone_w = 375 / width_short;
    //
    [DataProcessing shareSingle].ratio_w = ratio_w;
    [DataProcessing shareSingle].ratio_h = ratio_h;
    [DataProcessing shareSingle].ratio_hw = height_long/width_short;
    //
    [DataProcessing shareSingle].ratio_iPhone_w = ratio_iPhone_w;
    //
//    self.view.backgroundColor = [UIColor whiteColor];
    UIImage* image = [UIImage imageNamed:@"bookcase_bg_cell.png"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];
    //
    [self.view setClipsToBounds:YES];
    //NSLog(@"origin did  load  -----------  %s",__func__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addBackView
{
    [self.view addSubview:[self newClickViewImage:@"btn_back_normal.png" Target:self selecter:@selector(tapBack)]];
}

- (UIView*)newClickViewImage:(NSString*)imgStr Target:(id)target selecter:(SEL)selecter
{
    CGFloat btnwidth = 44;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        btnwidth = 44/ratio_w;
    }
    return [self newClickViewImage:imgStr Target:target selecter:selecter clickSize:CGSizeMake(80/ratio_w, 56/ratio_w) imgSize:CGSizeMake(btnwidth, btnwidth)];
}

- (UIView*)newClickViewImage:(NSString*)imgStr Target:(id)target selecter:(SEL)selecter clickSize:(CGSize)size imgSize:(CGSize)sizeImg
{
    CGFloat w = size.width;
    CGFloat h = size.height;
    CGFloat top = 0;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        h = ceil(h*1.2);
        top = 20;
    }
    UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, top, w, h)];
    view.backgroundColor = [UIColor clearColor];
    //[self.view addSubview:view];
    //
    TLTapImageView* imgv = [[TLTapImageView alloc] initWithFrame:CGRectMake(0, 0, sizeImg.width, sizeImg.height)];
    imgv.normalImage = [UIImage imageNamed:imgStr];
    //imgv.selectImage = [UIImage imageNamed:@"btn_back_down.png"];
    imgv.image = imgv.normalImage;
    imgv.center = CGPointMake(w/2, h/2);
    [view addSubview:imgv];
    //
    if (selecter && target) {
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:selecter];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        [view addGestureRecognizer:tap];
        tap.delegate = [TLGestureRecognizerDelegate shareSingleTapView];
    }
    return view;
}

- (void)addSwipeBackGesture
{
    //UISwipeGestureRecognizer
    UISwipeGestureRecognizer* handGR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didHandSwipeToRight:)];
    [handGR setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:handGR];
}

- (void)tapBack
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dealloc_My];
}

- (void)didHandSwipeToRight:(UISwipeGestureRecognizer*)swipe
{
    [self tapBack];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    
    //telen 统计
    //[UMSAgent startTracPage:_tracPageName];
    //if(_tracPageName)[NSObject msgToClassName:@"UMSAgent" menthed:@"startTracPage:" refs:@[_tracPageName] needReturnValue:NO];
    //
    //NSLog(@"origin will appear  -----------  %s",__func__);
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
#ifdef JReaderSDKControl
#else
#ifdef JR_PJ
    if ([self isKindOfClass:[HomePageViewController class]] || [self isKindOfClass:[SeriesViewController class]] || [self isKindOfClass:[MoreBooksViewController class]] || [self isKindOfClass:[LibraryViewController class]] || [self isKindOfClass:[AboutMeViewController class]]) {
        if ([self isKindOfClass:[MoreBooksViewController class]]){
            MoreBooksViewController *moreVC = (MoreBooksViewController*)self;
            if (moreVC.type == MoreBooks_Type_mybooks) {
                [[RootViewController shareLastInstance] hiddenPlayerEntrance];
                return;
            }
        }
        [[RootViewController shareLastInstance] showPlayerEntrance];
    }
#endif
#endif
}

- (void)showAlertMsg:(NSString *)msg title:(NSString *)title
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"sure", ""), nil];
    [alert show];
}

- (void)viewWillDisappear:(BOOL)animated
{
    //telen 统计
    //[UMSAgent endTracPage:_tracPageName];
    //if(_tracPageName)[NSObject msgToClassName:@"UMSAgent" menthed:@"endTracPage:" refs:@[_tracPageName] needReturnValue:NO];
    //
    [super viewWillDisappear:animated];
}

- (void)applicationDidBecomeActive:(UIApplication *)application{};
- (void)applicationDidEnterBackground:(UIApplication *)application{};
- (void)applicationWillEnterForeground:(UIApplication *)application{};
- (void)applicationWillResignActive:(UIApplication *)application{};

//- (void)presentToPopViewController:(PopBaseViewController*)popvc
//{
//    BOOL isModal_OK = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
//    if (isModal_OK) {
//        popvc.modalPresentationStyle = UIModalPresentationCustom;
//        popvc.transitioningDelegate = self;
//    }else{
//        popvc.modalPresentationStyle = UIModalPresentationNone;
//    }
//    [self presentViewController:popvc animated:YES completion:nil];
//}

- (void)presentToPopViewController:(PopBaseViewController*)popvc
{
    if (popvc) {
        popvc.modalPresentationStyle = UIModalPresentationCustom;
        popvc.transitioningDelegate = self;
        [self.navigationController presentViewController:popvc animated:YES completion:nil];
    }
}

- (void)vcTransitions_AnimationPresent_Begin:(UIViewController *)presentVC
{
    PopBaseViewController* popvc = (PopBaseViewController*)presentVC;
    [popvc addSuperViewConstraints];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    _animation.type =  AnimationTypePresent;
    return _animation;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    _animation.type =  AnimationTypeDismiss;
    return _animation;
}

- (void)refreshUI {
    
}

- (void)refreshData {
    
}

- (void)refreshNaviBar {
    
}

- (void)loaclCallPreRefresh {
    
}

@end

#pragma mark-
@implementation BaseVCManager

+ (NSMutableArray*)getBaseVCManger_vcs {
    static __strong NSMutableArray * BaseVCManager_vcs = nil;
    if (!BaseVCManager_vcs) {
        BaseVCManager_vcs = [NSMutableArray new];
    }
    return BaseVCManager_vcs;
}


+ (void)registerBaseVC:(BaseViewController *)vc {
    if ([vc isKindOfClass:[BaseViewController class]]) {
        NSValue* value = [NSValue valueWithNonretainedObject:vc];
        [[BaseVCManager getBaseVCManger_vcs] addObject:value];
    }
}

+ (void)unRegisterBaseVC:(BaseViewController *)vc {
    NSArray* arr = [NSArray arrayWithArray:[BaseVCManager getBaseVCManger_vcs]];
    for (NSValue* value in arr) {
        if([value nonretainedObjectValue] == vc){
            [[BaseVCManager getBaseVCManger_vcs] removeObject:value];
        }
    }
}

+ (void)refreshAllBaseVCUI {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        for (NSValue* value in [BaseVCManager getBaseVCManger_vcs]) {
            BaseViewController* notice = [value nonretainedObjectValue];
            if ([notice respondsToSelector:@selector(refreshUI)]) {
                [notice refreshUI];
            }
        }
    });
}

+ (void)refreshDataForAllBaseVC {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (NSValue* value in [BaseVCManager getBaseVCManger_vcs]) {
            BaseViewController* notice = [value nonretainedObjectValue];
            if ([notice respondsToSelector:@selector(refreshData)] && ![notice isKindOfClass:[ReadBookVOrH_VC class]]) {
                [notice refreshData];
            }
        }
    });
}

+ (void)refreshDataForAllBaseVCWithOutReadVC {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (NSValue* value in [BaseVCManager getBaseVCManger_vcs]) {
            BaseViewController* notice = [value nonretainedObjectValue];
            if ([notice respondsToSelector:@selector(refreshData)] && ![notice isKindOfClass:[ReadBookVOrH_VC class]]) {
                [notice refreshData];
            }
        }
    });
}

+ (void)localcallPreRefresh {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        for (NSValue* value in [BaseVCManager getBaseVCManger_vcs]) {
            BaseViewController* notice = [value nonretainedObjectValue];
            if ([notice respondsToSelector:@selector(loaclCallPreRefresh)] && ![notice isKindOfClass:[ReadBookVOrH_VC class]]) {
                [notice loaclCallPreRefresh];
            }
        }
    });
}

@end
